{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/llm/dashscope.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DashScope LLMS"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook, we show how to use the DashScope LLM models in LlamaIndex. Check out the [DashScope site](https://dashscope.aliyun.com/) or the [documents](https://help.aliyun.com/zh/dashscope/developer-reference/api-details).\n",
    "\n",
    "If you're opening this Notebook on colab, you will need to install LlamaIndex 🦙 and the DashScope Python SDK."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index-llms-dashscope"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Usage\n",
    "\n",
    "You will need to login [DashScope](https://dashscope.aliyun.com/) an create a API. Once you have one, you can either pass it explicitly to the API, or use the `DASHSCOPE_API_KEY` environment variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "env: DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY\n"
     ]
    }
   ],
   "source": [
    "%env DASHSCOPE_API_KEY=YOUR_DASHSCOPE_API_KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"DASHSCOPE_API_KEY\"] = \"YOUR_DASHSCOPE_API_KEY\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Initialize `DashScope` Object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.dashscope import DashScope, DashScopeGenerationModels\n",
    "\n",
    "dashscope_llm = DashScope(model_name=DashScopeGenerationModels.QWEN_MAX)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Call `complete` with a prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Making a basic vanilla cake from scratch is a simple and enjoyable process. Here's a step-by-step recipe for a classic vanilla sponge cake:\n",
      "\n",
      "**Ingredients:**\n",
      "- 2 cups (240g) all-purpose flour\n",
      "- 1 ¾ cups (350g) granulated sugar\n",
      "- 3 teaspoons baking powder\n",
      "- ½ teaspoon salt\n",
      "- ⅓ cup (80g) unsalted butter, softened\n",
      "- 1 cup (240ml) whole milk, at room temperature\n",
      "- 2 teaspoons pure vanilla extract\n",
      "- 3 large eggs, at room temperature\n",
      "\n",
      "**Instructions:**\n",
      "\n",
      "1. **Preheat the Oven**: Preheat your oven to 350°F (175°C). Grease two 9-inch round cake pans with butter or cooking spray, then line the bottoms with parchment paper.\n",
      "\n",
      "2. **Dry Ingredients**: In a large mixing bowl, sift together the flour, sugar, baking powder, and salt. Make sure everything is well combined.\n",
      "\n",
      "3. **Cream the Butter and Sugar**: In another large bowl, beat the softened butter until creamy. Gradually add the sugar and continue beating until light and fluffy, about 3-4 minutes.\n",
      "\n",
      "4. **Add Eggs and Vanilla**: Beat in the eggs one at a time, making sure each egg is fully incorporated before adding the next. Mix in the vanilla extract.\n",
      "\n",
      "5. **Combine Wet and Dry**: With the mixer on low speed, alternately add the dry ingredients mixture and milk into the wet mixture in three parts, starting and ending with the flour mixture. Be careful not to overmix; stop as soon as the ingredients are just combined.\n",
      "\n",
      "6. **Pour and Bake**: Divide the batter evenly between the prepared pans. Smooth the tops with a spatula. Bake for 25-30 minutes, or until a toothpick inserted into the center of each cake comes out clean.\n",
      "\n",
      "7. **Cool the Cake**: Remove cakes from the oven and let them cool in their pans for about 10 minutes. Then, remove from the pans and transfer onto wire racks to cool completely.\n",
      "\n",
      "8. **Frosting and Assembly**: Once cooled, you can frost and assemble the cake with your favorite frosting, such as buttercream. Place one cake layer on a plate or cake stand, spread frosting over the top, then place the second cake layer on top. Frost the top and sides of the cake as desired.\n",
      "\n",
      "Remember, this is a basic vanilla cake recipe that can be customized with different flavors or toppings. Always read through the entire recipe before beginning and ensure all ingredients are at room temperature for best results.\n"
     ]
    }
   ],
   "source": [
    "resp = dashscope_llm.complete(\"How to make cake?\")\n",
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Call `stream_complete`` with a prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Baking a cake can be a fun and rewarding experience! Here's a simple recipe for a classic vanilla sponge cake:\n",
      "\n",
      "**Ingredients:**\n",
      "- 2 cups (240g) all-purpose flour\n",
      "- 2 teaspoons baking powder\n",
      "- 1/2 teaspoon salt\n",
      "- 1 cup (2 sticks or 226g) unsalted butter, at room temperature\n",
      "- 1 3/4 cups (350g) granulated sugar\n",
      "- 4 large eggs, at room temperature\n",
      "- 2 teaspoons pure vanilla extract\n",
      "- 1 1/4 cups (300ml) whole milk, at room temperature\n",
      "\n",
      "**Instructions:**\n",
      "\n",
      "1. **Preheat the Oven**: Preheat your oven to 350°F (175°C). Grease two 9-inch (23cm) round cake pans with butter or cooking spray, then line the bottoms with parchment paper.\n",
      "\n",
      "2. **Mix Dry Ingredients**: In a medium bowl, sift together the flour, baking powder, and salt. Set aside.\n",
      "\n",
      "3. **Cream Butter and Sugar**: In a large mixing bowl or using a stand mixer, cream the butter until it is light and fluffy. Gradually add in the sugar and continue beating until the mixture is pale and well-combined, about 3-5 minutes.\n",
      "\n",
      "4. **Add Eggs and Vanilla**: Beat in the eggs one at a time, making sure each egg is fully incorporated before adding the next. Add the vanilla extract and mix well.\n",
      "\n",
      "5. **Combine Wet and Dry**: With the mixer on low speed, alternately add the dry ingredients mixture and the milk to the butter-sugar mixture, starting and ending with the dry ingredients. Mix just until combined; do not overmix.\n",
      "\n",
      "6. **Pour and Bake**: Divide the batter evenly between the prepared pans. Smooth the tops with a spatula. Bake for 25-30 minutes or until a toothpick inserted into the center of the cakes comes out clean.\n",
      "\n",
      "7. **Cool and Frost**: Remove the cakes from the oven and let them cool in their pans for about 10 minutes. Then, remove the cakes from the pans and transfer to a wire rack to cool completely. Once cooled, you can frost and decorate as desired.\n",
      "\n",
      "For frosting, you could make a basic buttercream by beating softened butter with powdered sugar, vanilla, and a little milk until smooth and spreadable.\n",
      "\n",
      "Remember that every oven behaves differently, so keep an eye on your cake while it bakes. Enjoy your homemade cake!\n",
      "\n",
      "**Optional Steps:**\n",
      "- For extra flavor, you can add lemon zest, cocoa powder, or other flavorings to the batter.\n",
      "- Level the cakes with a serrated knife before stacking and frosting to ensure an even surface.\n",
      "- Chill the cakes before frosting to help prevent crumbs from getting mixed into the frosting."
     ]
    }
   ],
   "source": [
    "responses = dashscope_llm.stream_complete(\"How to make cake?\")\n",
    "for response in responses:\n",
    "    print(response.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Call `chat` with a list of messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant: Baking a cake from scratch is a fun and rewarding experience! Here's a simple recipe for a classic vanilla cake:\n",
      "\n",
      "**Ingredients:**\n",
      "- 2 and 1/4 cups (280g) all-purpose flour\n",
      "- 1 and 1/2 cups (300g) granulated sugar\n",
      "- 3 teaspoons baking powder\n",
      "- 1/2 teaspoon salt\n",
      "- 1 cup (2 sticks or 226g) unsalted butter, at room temperature\n",
      "- 1 cup (240ml) whole milk, at room temperature\n",
      "- 4 large eggs, at room temperature\n",
      "- 2 teaspoons pure vanilla extract\n",
      "\n",
      "**For the frosting (optional):**\n",
      "- 1 cup (2 sticks or 226g) unsalted butter, softened\n",
      "- 4 cups (480g) powdered sugar\n",
      "- 2 teaspoons vanilla extract\n",
      "- 3-5 tablespoons milk\n",
      "\n",
      "**Instructions:**\n",
      "\n",
      "1. **Preheat Oven and Prepare Pan**: Preheat your oven to 350°F (175°C). Grease two 9-inch round cake pans with butter or cooking spray. Dust them lightly with flour and tap out any excess.\n",
      "\n",
      "2. **Mix Dry Ingredients**: In a large mixing bowl, whisk together the flour, sugar, baking powder, and salt until well combined.\n",
      "\n",
      "3. **Cream Butter and Sugar**: In another large bowl, using an electric mixer on medium speed, beat the butter until creamy. Gradually add in the sugar and continue beating until light and fluffy, about 3-5 minutes.\n",
      "\n",
      "4. **Add Eggs and Vanilla**: Beat in the eggs one at a time, making sure each egg is fully incorporated before adding the next. Stir in the vanilla extract.\n",
      "\n",
      "5. **Alternate Wet and Dry Ingredients**: With the mixer on low speed, alternately add the dry ingredients mixture and milk to the wet mixture, starting and ending with the dry ingredients. Mix until just combined; do not overmix.\n",
      "\n",
      "6. **Pour Batter and Bake**: Divide the batter evenly between the prepared pans. Smooth the tops. Bake for 25-30 minutes or until a toothpick inserted into the center of the cakes comes out clean.\n",
      "\n",
      "7. **Cool Cakes**: Remove cakes from the oven and let them cool in the pans for about 10 minutes. Then, carefully invert the cakes onto wire racks to cool completely.\n",
      "\n",
      "8. **Make Frosting (Optional)**: In a separate bowl, beat butter until smooth. Gradually add powdered sugar, vanilla extract, and enough milk to reach your desired consistency. Beat until smooth and creamy.\n",
      "\n",
      "9. **Assemble Cake**: Once the cakes are cooled, place one layer on a plate or cake stand. Spread a thick layer of frosting on top. Place the second cake layer on top and cover the entire cake with the remaining frosting.\n",
      "\n",
      "Enjoy your homemade vanilla cake!\n",
      "\n",
      "Remember, this is just a basic recipe. You can customize it by adding food coloring, different extracts, or mix-ins like chocolate chips or fruit. Always be mindful of adjusting baking times if you're using different sized pans.\n"
     ]
    }
   ],
   "source": [
    "from llama_index.core.base.llms.types import MessageRole, ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=MessageRole.SYSTEM, content=\"You are a helpful assistant.\"\n",
    "    ),\n",
    "    ChatMessage(role=MessageRole.USER, content=\"How to make cake?\"),\n",
    "]\n",
    "resp = dashscope_llm.chat(messages)\n",
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Using `stream_chat` "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Baking a cake from scratch is a fun and delicious activity! Here's a simple recipe for a classic vanilla cake:\n",
      "\n",
      "**Ingredients:**\n",
      "- 2 cups (240g) all-purpose flour\n",
      "- 2 teaspoons baking powder\n",
      "- 1/2 teaspoon baking soda\n",
      "- 1/2 teaspoon salt\n",
      "- 1 cup (2 sticks or 226g) unsalted butter, at room temperature\n",
      "- 1 3/4 cups (350g) granulated sugar\n",
      "- 4 large eggs, at room temperature\n",
      "- 2 teaspoons pure vanilla extract\n",
      "- 1 cup (240ml) whole milk, at room temperature\n",
      "\n",
      "**Instructions:**\n",
      "\n",
      "1. **Preheat the Oven**: Preheat your oven to 350°F (175°C). Grease two 9-inch round cake pans with butter or cooking spray and line the bottoms with parchment paper.\n",
      "\n",
      "2. **Dry Ingredients Mix**: In a medium bowl, sift together the flour, baking powder, baking soda, and salt. Set aside.\n",
      "\n",
      "3. **Creaming Butter and Sugar**: In a large mixing bowl or using a stand mixer, beat the softened butter until creamy. Gradually add in the sugar and continue beating until light and fluffy, about 3-5 minutes.\n",
      "\n",
      "4. **Egg Incorporation**: Add the eggs one at a time, beating well after each addition. Stir in the vanilla extract.\n",
      "\n",
      "5. **Dry & Wet Ingredients Combine**: Add the dry ingredients mixture to the wet ingredients in three parts, alternating with the milk, beginning and ending with the dry ingredients. Mix on low speed just until combined. Do not overmix; a few lumps are okay.\n",
      "\n",
      "6. **Bake**: Divide the batter evenly between the prepared pans. Smooth out the tops with a spatula. Bake for 25-30 minutes or until a toothpick inserted into the center of the cakes comes out clean.\n",
      "\n",
      "7. **Cool**: Remove the cakes from the oven and let them cool in their pans for about 10 minutes. Then, invert onto wire racks to cool completely.\n",
      "\n",
      "8. **Frosting and Assembly**: Once cooled, you can frost the cake with your choice of frosting - such as a classic buttercream. Place one cake layer on a plate or cake stand, spread frosting over it, then place the second layer on top. Frost the top and sides of the cake as desired.\n",
      "\n",
      "Enjoy your homemade vanilla cake!\n",
      "\n",
      "**Note:** You can customize this basic recipe by adding food coloring, different flavor extracts, or incorporating mix-ins like chocolate chips or fruit. Adjust baking times if you're making cupcakes or larger cakes."
     ]
    }
   ],
   "source": [
    "responses = dashscope_llm.stream_chat(messages)\n",
    "for response in responses:\n",
    "    print(response.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Multiple rounds conversation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant: Baking a cake is a fun and creative process! Here's a simple recipe for a classic vanilla sponge cake. You will need:\n",
      "\n",
      "Ingredients:\n",
      "- 1 and 1/2 cups (190g) all-purpose flour\n",
      "- 1 cup (200g) granulated sugar\n",
      "- 2 teaspoons baking powder\n",
      "- 1/2 teaspoon salt\n",
      "- 1/2 cup (1 stick or 113g) unsalted butter, softened\n",
      "- 2 large eggs, room temperature\n",
      "- 2 teaspoons pure vanilla extract\n",
      "- 3/4 cup (180ml) whole milk, at room temperature\n",
      "\n",
      "For the frosting (optional):\n",
      "- 1 cup (226g) unsalted butter, softened\n",
      "- 4 cups (400g) powdered sugar\n",
      "- 2 tablespoons heavy cream or milk\n",
      "- 2 teaspoons vanilla extract\n",
      "\n",
      "Instructions:\n",
      "\n",
      "1. Preheat your oven to 350°F (175°C). Grease two 9-inch round cake pans with butter or cooking spray, then line the bottoms with parchment paper.\n",
      "\n",
      "2. In a medium bowl, whisk together the flour, sugar, baking powder, and salt until well combined.\n",
      "\n",
      "3. In a large mixing bowl, beat the softened butter until creamy. Gradually add in the sugar and continue beating until light and fluffy, about 3 minutes.\n",
      "\n",
      "4. Add in the eggs one at a time, beating well after each addition. Mix in the vanilla extract.\n",
      "\n",
      "5. With the mixer on low speed, alternate adding the flour mixture and milk, starting and ending with the flour mixture. Beat until just combined, being careful not to overmix.\n",
      "\n",
      "6. Divide the batter evenly between the prepared pans.\n",
      "\n",
      "7. Bake for 25 to 30 minutes or until a toothpick inserted into the center of each cake comes out clean.\n",
      "\n",
      "8. Let the cakes cool in their pans for 10 minutes, then remove them from the pans and place them onto wire racks to cool completely.\n",
      "\n",
      "To make the frosting (if desired):\n",
      "\n",
      "1. In a large mixing bowl, beat the softened butter until smooth.\n",
      "2. Gradually add in the powdered sugar, mixing well after each addition.\n",
      "3. Stir in the heavy cream or milk and vanilla extract. Beat on high speed until the frosting is smooth and creamy.\n",
      "\n",
      "Assembling the Cake:\n",
      "\n",
      "1. Once the cakes are cooled, place one layer on a plate or cake stand. Spread a generous amount of frosting over the top.\n",
      "2. Place the second cake layer on top of the frosting, bottom-side up to create a flat surface.\n",
      "3. Frost the top and sides of the cake with the remaining frosting as desired.\n",
      "\n",
      "Enjoy your homemade vanilla sponge cake!\n",
      "\n",
      "Remember, this is just a basic recipe and you can customize it by adding food coloring, different flavorings, or toppings to suit your taste. Always follow the specific instructions for more complex recipes or those that use different ingredients like chocolate or fruit.\n",
      "assistant: To make a cake without sugar, you can substitute sugar with alternative natural sweeteners. Here's a recipe for a simple sugar-free vanilla sponge cake using honey as a sweetener:\n",
      "\n",
      "Ingredients:\n",
      "- 1 and 1/2 cups (190g) all-purpose flour\n",
      "- 3/4 cup (225g) honey (use mild-flavored honey like clover or acacia)\n",
      "- 2 teaspoons baking powder\n",
      "- 1/2 teaspoon salt\n",
      "- 1/2 cup (1 stick or 113g) unsalted butter, softened\n",
      "- 2 large eggs, room temperature\n",
      "- 2 teaspoons pure vanilla extract\n",
      "- 3/4 cup (180ml) whole milk, at room temperature\n",
      "\n",
      "Instructions:\n",
      "\n",
      "1. Preheat your oven to 350°F (175°C). Grease two 9-inch round cake pans with butter or cooking spray, then line the bottoms with parchment paper.\n",
      "\n",
      "2. In a medium bowl, whisk together the flour, baking powder, and salt.\n",
      "\n",
      "3. In a large mixing bowl, beat the softened butter and honey until light and fluffy, about 3-4 minutes. Honey is more liquid than sugar so it may take a little longer to incorporate.\n",
      "\n",
      "4. Add in the eggs one at a time, beating well after each addition. Mix in the vanilla extract.\n",
      "\n",
      "5. With the mixer on low speed, alternate adding the flour mixture and milk, starting and ending with the flour mixture. Beat until just combined, being careful not to overmix.\n",
      "\n",
      "6. Divide the batter evenly between the prepared pans.\n",
      "\n",
      "7. Bake for 25 to 30 minutes or until a toothpick inserted into the center of each cake comes out clean.\n",
      "\n",
      "8. Let the cakes cool in their pans for 10 minutes, then remove them from the pans and place them onto wire racks to cool completely.\n",
      "\n",
      "Note: Baking with honey can result in a moister cake that browns faster. You might need to adjust the baking time accordingly and monitor the color of the cake while it bakes.\n",
      "\n",
      "Keep in mind that honey is still a form of carbohydrate and has calories. For a completely sugar-free option, you could use erythritol or stevia-based sweeteners, but be aware that these will affect the texture and taste differently compared to traditional sugar or honey. Adjust the amount according to the specific sweetener’s conversion ratio to sugar, and follow the instructions provided by the manufacturer.\n",
      "\n",
      "For frosting, you can also create a sugar-free version using cream cheese or whipped cream sweetened with a sugar substitute, if desired.\n"
     ]
    }
   ],
   "source": [
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=MessageRole.SYSTEM, content=\"You are a helpful assistant.\"\n",
    "    ),\n",
    "    ChatMessage(role=MessageRole.USER, content=\"How to make cake?\"),\n",
    "]\n",
    "# first round\n",
    "resp = dashscope_llm.chat(messages)\n",
    "print(resp)\n",
    "\n",
    "# add response to messages.\n",
    "messages.append(\n",
    "    ChatMessage(role=MessageRole.ASSISTANT, content=resp.message.content)\n",
    ")\n",
    "\n",
    "messages.append(\n",
    "    ChatMessage(role=MessageRole.USER, content=\"How to make it without sugar\")\n",
    ")\n",
    "# second round\n",
    "resp = dashscope_llm.chat(messages)\n",
    "print(resp)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "gemini.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
